package com.zkt.weichat.handler;

import com.zkt.weichat.redis.RedisUtil;
import com.zkt.weichat.utils.CaptchaGeneratorUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 赵开泰
 * @program jc-club
 * @date 2025/3/23 01:35
 * @description 接收消息实现handler
 **/

@Component
@Slf4j
public class ReceiveTextMsgHandler implements WeichatMsgHandler {
	
	@Resource
	private RedisUtil redisUtil;
	
	private static final String KEY_WORD = "验证码";
	
	private static final String CAPTCHA_PREFIX = "captcha";
	
	private static final String OPEN_KEY_PREFIX = "openId:";
	
	private static final long EXIST_TIME = 5L;
	
	@Override
	public WeichatMsgTypeEnum getMsgType() {
		return WeichatMsgTypeEnum.TEXT_MSG;
	}
	
	@Override
	public String dealMsg(Map<String, String> msgMap) {
		log.info("接收到文本消息");
		
		String content = msgMap.get("Content");
		if (!KEY_WORD.equals(content)) {
			return "";
		}
		
		String toUserName = msgMap.get("ToUserName");
		String fromUserName = msgMap.get("FromUserName");
		
		String captcha = CaptchaGeneratorUtil.generate();
		
		String openKey = redisUtil.buildKey(CAPTCHA_PREFIX, fromUserName);
		String captchaKey = redisUtil.buildKey(CAPTCHA_PREFIX, captcha);
		
		if (redisUtil.exist(openKey)) {
			redisUtil.del(redisUtil.get(openKey));
		}
		
		redisUtil.setNx(openKey, captcha, EXIST_TIME, TimeUnit.MINUTES);
		redisUtil.setNx(captchaKey, fromUserName, EXIST_TIME, TimeUnit.MINUTES);
		
		String captchaContent = "您当前的验证码是：" + captcha + "，5分钟有效。";
		
		return "<xml>\n" +
				"  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
				"  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
				"  <CreateTime>1348831860</CreateTime>\n" +
				"  <MsgType><![CDATA[text]]></MsgType>\n" +
				"  <Content><![CDATA[" + captchaContent + "]]></Content>\n" +
				"</xml>";
	}
}